import {
  OnGatewayConnection,
  OnGatewayDisconnect,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway()
export class WebsocketGateway
  implements OnGatewayConnection, OnGatewayDisconnect
{
  // 使用WebSocketServer装饰器获取Socket.IO服务器实例
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('message')
  handleMessage(client: Socket, payload: any) {
    console.log('接收消息：', payload);

    // 发送消息
    this.server.emit('message', 'hi client');

    // 关闭连接
    client.disconnect();
  }

  @SubscribeMessage('chat')
  handleChat(client: Socket, payload: any) {
    console.log('请求头：', client.request.headers);
    console.log('远端地址：', client.request.connection.remoteAddress);

    console.log('[chat]接收消息：', payload);

    // 自定义事件发送消息
    this.server.emit('chat', 'hi client');

    // 关闭连接
    client.disconnect();
  }

  handleConnection(client: Socket) {
    // 监听连接开启事件
    console.log(`客户端已连接：${client.id}`);
  }

  handleDisconnect(client: Socket) {
    // 监听连接关闭事件
    console.log(`客户端已断开连接：${client.id}`);
  }
}
